package com.newfiber.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newfiber.common.core.exception.ServiceException;
import com.newfiber.common.core.web.service.BaseServiceImpl;
import com.newfiber.system.domain.AppMenuCollect;
import com.newfiber.system.domain.request.appMenuCollect.AppMenuCollectQueryRequest;
import com.newfiber.system.domain.request.appMenuCollect.AppMenuCollectSaveRequest;
import com.newfiber.system.mapper.AppMenuCollectMapper;
import com.newfiber.system.service.IAppMenuCollectService;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * APP菜单收藏Service业务层处理
 * 
 * @author X.K
 * @date 2023-03-29
 */
@Service
public class AppMenuCollectServiceImpl extends BaseServiceImpl<AppMenuCollectMapper, AppMenuCollect> implements IAppMenuCollectService {

    @Resource
    private AppMenuCollectMapper appMenuCollectMapper;

    @Override
    public synchronized boolean collectAndUnCollect(AppMenuCollectSaveRequest request) {
    	AppMenuCollect existedAppMenuCollect = selectDetail(request.getAppMenuId(), request.getUserId());
    	if(null == existedAppMenuCollect){
		    AppMenuCollect appMenuCollect = new AppMenuCollect();
		    BeanUtils.copyProperties(request, appMenuCollect);
		    save(appMenuCollect);
	    }else{
    		removeById(existedAppMenuCollect.getId());
	    }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
	    return deleteLogic(ids);
    }

    @Override
    public AppMenuCollect selectDetail(Long id) {
        AppMenuCollect appMenuCollect = appMenuCollectMapper.selectById(id);
        if(null == appMenuCollect){
	        throw new ServiceException(String.format("%s ID=%s 的记录不存在", this.getClass().getSimpleName(), id));
        }
        return appMenuCollect;
    }

    private AppMenuCollect selectDetail(Long appMenuId, Long userId){
	    QueryWrapper<AppMenuCollect> queryWrapper = new QueryWrapper<AppMenuCollect>().
		    eq("app_menu_id", appMenuId).eq("user_id", userId).last("limit 1");
	    return getOne(queryWrapper);
    }

    @Override
    public List<AppMenuCollect> selectPage(AppMenuCollectQueryRequest request) {
        return appMenuCollectMapper.selectByCondition(request);
    }

    @Override
    public List<AppMenuCollect> selectList(AppMenuCollectQueryRequest request) {
        return appMenuCollectMapper.selectByCondition(request);
    }

}
